<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
          <el-form-item prop="name">
            <el-select v-model="filters.name"  placeholder="请选择等级名称" style="width:215px">
                <!-- <el-option label="请选择需求分类" value=""></el-option> -->
                <el-option
                      v-for="item in levelList"
                    :key="item"
                    :label="item"
                    :value="item">
                    </el-option>
            </el-select>
        </el-form-item>
        <el-form-item prop="time">
          <el-date-picker
              v-model="filters.startTime"
              type="date"
              :editable="false"
              prefix-icon="el-icon-caret-bottom"
              value-format="yyyy-MM-dd"
              :clearable='false'
              placeholder="请选择开始时间">
          </el-date-picker>
          <span style="padding: 0 3px">--</span>
          <el-date-picker
              v-model="filters.endTime"
              type="date"
              :editable="false"
              prefix-icon="el-icon-caret-bottom"
              value-format="yyyy-MM-dd"
              :clearable='false'
              placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>

        <el-row>
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetFormBtn('filters')" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
    </div>

    <div>
      <!--表格栏-->
      <el-table
        :data="table.content"
        @selection-change="selectionChange"
        :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
        :show-overflow-tooltip="table.showOverflowTooltip"
        max-height="500px"
        :size="table.size"
        :align="table.align"
        style="width:100%;"
      >
        <el-table-column type="selection" width="50" fixed="left"></el-table-column>

        <template v-for="column in filterColumns">
          <el-table-column
            header-align="center"
            align="center"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :key="column.prop"
            :type="column.type"
            :formatter="column.formatter"
            :sortable="column.sortable==null?true:column.sortable"
          >
            <template slot-scope="scope">
              <template v-if="!column.render">
                <template v-if="column.formatter">
                  <div
                    v-html="column.formatter(scope.row, column,scope.row[column.prop],scope.index)"
                  ></div>
                </template>
                <template v-else>
                  <span>{{scope.row[column.prop]}}</span>
                </template>
              </template>
              <template v-else>
                <expand-dom
                  :column="column"
                  :row="scope.row"
                  :render="column.render"
                  :index="index"
                ></expand-dom>
              </template>
            </template>
          </el-table-column>
        </template>

        <el-table-column
          :label="$t('action.operation')"
          width="185"
          fixed="right"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <kt-button
              icon="fa fa-edit"
              :label="$t('action.edit')"
              :size="size"
              @click="handleEdit(scope)"
            />
            <kt-button
              icon="fa fa-trash"
              :label="$t('action.delete')"
              :size="size"
              type="danger"
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页栏-->
      <div class="toolbar" style="padding:10px;">
        <kt-button
          :label="$t('action.batchDelete')"
          :size="size"
          type="danger"
          @click="handleBatchDelete()"
          :disabled="this.table.selections.length===0"
          style="float:left;"
        />
        <el-pagination
          layout="total, prev, pager, next, jumper,sizes"
          @current-change="refreshPageRequest"
          :current-page="table.pageRequest.pageNum"
          :page-size="table.pageRequest.pageSize"
          :total="table.totalSize"
          style="float:right;"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>

    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="40%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="120px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        
        <el-tabs :tab-position="tabPosition" style="height: auto;">
          <el-tab-pane label="基本信息">
            <el-form-item label="ID" prop="id" v-model="dataForm.id" v-if="false">
              <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-select v-model="dataForm.name"  placeholder="请选择等级名称" style="width:100%;" auto-complete="off">
                  <!-- <el-option label="请选择需求分类" value=""></el-option> -->
                  <el-option
                        v-for="item in levelList"
                      :key="item"
                      :label="item"
                      :value="item">
                      </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详情介绍" prop="dpic">
              <el-upload
                class="avatar-uploader"
                :action="imgUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess">
                <img v-if="dataForm.dpic" :src="dataForm.dpic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="LOGO" prop="logo">
              <el-upload
                class="avatar-uploader"
                :action="imgUrl"
                :show-file-list="false"
                :on-success="logohandleAvatarSuccess">
                <img v-if="dataForm.logo" :src="dataForm.logo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="dataForm.description" auto-complete="off" type="textarea" placeholder="请输入描述"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="会员权益">
            <el-form-item label="爆款折扣" prop="hot_discount">
              <el-input v-model.number="dataForm.hot_discount" auto-complete="off" type="age" placeholder="请输入爆款折扣"></el-input>
            </el-form-item>
            <el-form-item label="其他折扣" prop="other_discount">
              <el-input v-model.number="dataForm.other_discount" auto-complete="off" type="age" placeholder="请输入其他折扣"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="会员限制">
            <el-form-item label="限制人数" prop="limits">
              <el-input v-model.number="dataForm.limits" auto-complete="off" type="age" placeholder="请输入限制人数"></el-input>
            </el-form-item>
            <el-form-item label="邀请注册人数" prop="members">
              <el-input v-model.number="dataForm.members" auto-complete="off" type="age" placeholder="请输入邀请注册人数"></el-input>
            </el-form-item>
            <el-form-item label="是否下单">
              <el-radio v-model="dataForm.order_flg" label="1">是</el-radio>
              <el-radio v-model="dataForm.order_flg" label="0">否</el-radio>
            </el-form-item>
            <el-form-item label="一次性充值金额" prop="one_charge">
              <el-input v-model.number="dataForm.one_charge" auto-complete="off" type="age" placeholder="请输入一次性充值金额"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" auto-complete="off" type="textarea" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>


      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import CyTable from "@/views/Core/CyTable";
import KtButton from "@/views/Core/KtButton";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { format, formatDate } from "@/utils/datetime";
import { exportExcel } from "@/utils/excel";
export default {
  components: {
    PopupTreeInput,
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      imgUrl:this.utils.imgUploadUrl,
      tabPosition:"top",
      size: "small",
      filters: {
        name:"",
        startTime:"",
        endTime:'',
        t: "memberGrade",
        queryname: ""
      },
      levelList:["普通会员","PLUS会员","联盟会员"],
      table: {
        showOverflowTooltip: true,
        size: "mini",
        align: "left",
        totalSize: 0,
        content: [],
        // 分页信息
        pageRequest: {
          pageNum: 1,
          pageSize: 10
        },
        selections: []
      },
      pageResult: {},

      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        name: [{ required: true, message: "请选择等级名称", trigger: "change" }],
        description: [{ required: true, message: "请输入描述", trigger: "blur" }],
        dpic: [{ required: true, message: "详情介绍图未上传", trigger: "blur" }],
        logo: [{ required: true, message: "LOGO未上传", trigger: "blur" }],
        hot_discount: [{ required: true, message: "请输入爆款折扣", trigger: "blur" },{ type: 'number', message: '爆款折扣必须为数字值'}],
        other_discount: [{ required: true, message: "请输入其他折扣", trigger: "blur" },{ type: 'number', message: '其他折扣必须为数字值'}],
        limits: [{ required: true, message: "请输入限制人数", trigger: "blur" },{ type: 'number', message: '限制人数必须为数字值'}],
        members: [{ required: true, message: "请输入邀请注册人数", trigger: "blur" },{ type: 'number', message: '邀请注册人数必须为数字值'}],
        one_charge: [{ required: true, message: "请输入一次性充值金额	", trigger: "blur" },{ type: 'number', message: '一次性充值金额爆款折扣必须为数字值'}],
        order_flg: [{ required: true, message: "请选择是否下单", trigger: "blur" }],
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      // 新增编辑界面数据
      dataForm: {
        id: "",
        name: "",
        dpic: "",
        description:"",
        logo:"",
        order_flg:'0'
      },
      columns: [],
      filterColumns: []
    };
  },
  methods: {
    // 选择切换
    selectionChange: function(selections) {
      this.table.selections = selections;
    },

    // 换页刷新
    refreshPageRequest: function(pageNum) {
      this.table.pageRequest.pageNum = pageNum;
      this.findPage();
    },
    // 换页刷新
    handleSizeChange: function(pageSize) {
      this.table.pageRequest.pageSize = pageSize;
      this.table.pageRequest.pageNum = 1;
      this.findPage();
    },
    resetFormBtn(formName) {
      this.$refs[formName].resetFields();
      this.filters.startTime="";
      this.filters.endTime="";
      this.findPage();
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportData(this.filters, this.filterColumns, "系统参数");
        })
        .catch(() => {});
    },
    //excle导出
    exportData(filters, filterColumns, fileName) {
      if (filters == undefined || filters == null) {
        filters = {};
      }
      filters.start = null;
      filters.limit = null;
      this.utils.request.queryUserPage(filters, function(res) {
        if (fileName == undefined || fileName == null) {
          fileName = "excel-list";
        }

        fileName = fileName + "_" + formatDate(new Date(), "yyyyMMdd");

        exportExcel(res.rows, filterColumns, fileName);
      });
    },
    // 获取分页数据
    //分页查询 // 获取分页数据
    // 获取分页数据
    findPage: function(data) {
      var this_ = this;
      this.filters.start = this.table.pageRequest.pageNum;
      this.filters.limit = this.table.pageRequest.pageSize;
      this.utils.request.queryUserPage(this.filters, function(res) {
        if (res.rows == null) {
          res.rows = [];
        }
        this_.table.content = res.rows;
        this_.table.totalSize = Number(res.total);
      });
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      this.columns = [
        { prop: "id", label: "ID", minWidth: 50 },
        { prop: "name", label: "等级名称", minWidth: 100 },
        { prop: "logo", label: "logo", minWidth: 100,formatter:function(row, column,prop){
          return "<img style='width: 50px;' src='"+prop+"'>"
        }},
        { prop: "hot_discount", label: "爆款折扣", minWidth: 80 },
        { prop: "other_discount", label: "其他折扣", minWidth: 120 },
        { prop: "limits", label: "限制人数", minWidth: 100},
        { prop: "members", label: "邀请注册人数", minWidth: 90 },
        { prop: "one_charge", label: "一次性充值金额", minWidth: 120 },
        { prop: "order_flg", label: "是否下单", minWidth: 70,formatter:function(row, column,prop){
          if(prop == 0){
            return "否";
          }else{
            return "是";
          }
        }},
        { prop: "description", label: "描述", minWidth: 120 },
        { prop: "create_time", label: "创建时间", minWidth: 120 }
      ];

      var temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;

      this.findPage();
    },

    // 批量删除
    handleDelete: function(row) {
      let ids = row.id;
      this.delete(ids);
    },
    // 批量删除
    handleBatchDelete: function() {
      let ids = this.table.selections.map(item => item.id).toString();
      this.delete(ids);
    },
    delete: function(ids) {
      var params = {};
      params.t = "memberGrade";
      params.ids = ids;
      var this_ = this;
      this.utils.request.deleteUserInfo(params, function(res) {
        if (res.code == "0000") {
          this_.$message({ message: "操作成功", type: "success" });
          this_.findPage(null);
        } else {
          this_.$message({ message: "操作失败, " + res.msg, type: "error" });
        }
      });
    },
    // 显示新增界面
    handleAdd: function() {
      this.editDialogVisible = true;
      this.operation = true;
      this.resetForm("dataForm");
    },
    // 显示编辑界面
    handleEdit: function(params) {
      this.editDialogVisible = true;
      this.operation = false;
      this.$nextTick(function() {
        params.row.order_flg = params.row.order_flg+"";
        this.dataForm = Object.assign({}, params.row);
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);

            params.t = "memberGrade";
            var this_ = this;
            this.utils.request.editInfo(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });

                this_.$refs["dataForm"].resetFields();

                this_.editDialogVisible = false;

                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    //详情图上穿
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      // debugger;
      this.dataForm.dpic = res.data.imgUrl;
    },
    // logo上传
    logohandleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      // debugger;
      this.dataForm.logo = res.data.imgUrl;
    },
    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
    }
  },
  mounted() {
    this.initColumns();
  }
};
</script>

<style scoped>

  .el-icon-plus{
    border: 1px dashed #d9d9d9 !important;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
  }
  .el-icon-plus .el-upload:hover {
    border-color: #2F4554;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
 <<style   scoped>
  /deep/  .el-table .sort-caret.ascending {
  border-bottom-color: #FFF;
  top: 5px;
}
  /deep/  .el-table .sort-caret.descending {
  border-top-color: #FFF;
  bottom: 7px;
} 

 /deep/  .el-table .ascending .sort-caret.ascending {
    border-bottom-color: #2F4554;
}

 /deep/  .el-table .descending .sort-caret.descending {
    border-top-color: #2F4554;
}
 </style>